package saxon.gui.model.xml;

import com.google.common.collect.Lists;
import java.io.File;
import java.util.List;
import net.sf.saxon.s9api.DocumentBuilder;
import net.sf.saxon.s9api.Processor;
import net.sf.saxon.s9api.QName;
import net.sf.saxon.s9api.SaxonApiException;
import net.sf.saxon.s9api.XQueryCompiler;
import net.sf.saxon.s9api.XQueryEvaluator;
import net.sf.saxon.s9api.XQueryExecutable;
import net.sf.saxon.s9api.XdmAtomicValue;
import net.sf.saxon.s9api.XdmItem;
import net.sf.saxon.s9api.XdmValue;
import org.apache.log4j.Logger;

/**
 *
 * @author lennyn
 */
public class XQueryHelper implements XmlHelper {

	private final static Logger logger = Logger.getLogger(XQueryHelper.class);
	private final static Processor processor = new Processor(false);
	private final static DocumentBuilder docBuilder = processor.newDocumentBuilder();
	private final XQueryCompiler compiler = processor.newXQueryCompiler();
	private final XQueryExecutable executable;
	private final String defaultNS;

	public XQueryHelper(String query, String defaultNS) throws Exception {
		this.defaultNS = defaultNS;
		this.compiler.declareNamespace("", defaultNS);
		this.executable = compiler.compile(query);
	}

	@Override
	public XdmValue execute(File srcFile) throws Exception {
		XQueryEvaluator evaluator = executable.load();
		try {
			evaluator.setContextItem(docBuilder.build(srcFile));
			evaluator.setExternalVariable(
					new QName("__FILE__"),
					new XdmAtomicValue(srcFile.getCanonicalPath()));
			return evaluator.evaluate();
		}
		catch (SaxonApiException ex) {
			throw new XException(ex);
		}

	}

	List<String> executeAndGetString(File srcFile) throws Exception {
		List<String> res = Lists.newArrayList();
		for (XdmItem item : execute(srcFile)) {
			res.add(item.toString());
		}
		return res;
	}
}
